package com.itany.shop.factory;

import com.itany.shop.util.ParameterUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Author:shixiaojun@itany.com
 * Date:2022/4/14 14:01
 * Version:1.0-SNAPSHOT
 * Description:
 */
public class ObjectFactory {

    private static Map<String,Object> objs;

    static{
        objs = new HashMap<>();
        BufferedReader br = null;
        try {
            br = new BufferedReader(
                    new InputStreamReader(
                            ObjectFactory
                                    .class
                                    .getClassLoader()
                                    .getResourceAsStream("beans.properties")));
            String line = null;
            while((line = br.readLine()) != null){
                // 考虑空行问题
                // 只有当不是空行的时候,需要根据等号进行分割
                // 将其分割成key-value两部分
                if(!ParameterUtil.isNull(line)){
                    String[] arr = line.split("=");
                    String key = arr[0];
                    String value = arr[1];
                    // 其value需要通过反射映射成具体的对象
                    // 且对象的实例化做成单例的
                    // 即一个对象,只实例化一次
                    objs.put(key,Class.forName(value).newInstance());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("ObjectFactory初始化失败");
        } finally {
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    throw new ExceptionInInitializerError("释放资源失败");
                }
            }
        }
    }

    public static Object getObject(String key){
        if(null == objs.get(key)){
            System.out.println("根据对应的key:"+key+"在配置文件中没有找到对应的配置");
            return null;
        }
        return objs.get(key);
    }

    public static void main(String[] args) {

    }
}
